<?php


namespace App\Services;

use App\Models\ZPituitaryUser;
use App\Models\ZZMed\ZUser;

class ManageDataService
{

    // 问卷答案表
    CONST ANSWER_TABLE = 'z_pituitary_answer';

    /**
     * 获取垂体病史信息
     * @param array $userId
     * @return array
     */
    public static function getPituitaryData(array $userId)
    {
        return ZPituitaryUser::query()
            ->from('z_pituitary_user_type')
            ->whereIn('user_id', $userId)
            ->get()
            ->toArray();
    }

    /**
     * 处理垂体病史数据
     *  1无功能瘤  2 GH瘤  3 PRL瘤 4 ACTH瘤 5 TSH瘤 6 GnH瘤（FSH/LH瘤）
     * @param $data
     * @param $count
     * @return array
     */
    public static function stuffPituitaryData($data, $count)
    {
        // 设置对于的key 对应 type
        $keysArr = [
            1 => 'one_sum',
            2 => 'two_sum',
            3 => 'three_sum',
            4 => 'four_sum',
            5 => 'five_sum',
            6 => 'sex_sum',
        ];

        $result = [
            'one_sum' => 0,
            'two_sum' => 0,
            'three_sum' => 0,
            'four_sum' => 0,
            'five_sum' => 0,
            'sex_sum' => 0
        ];

        foreach ($data as $item) {
            if (isset($keysArr[$item['type']])) {
                $result[$keysArr[$item['type']]]++;
            }
        }

        return $result;
    }

    /**
     * 解析时间
     * @param $start
     * @param $end
     * @return mixed
     */
    public static function stuffTime($start, $end)
    {
        $start = empty($start) ? date('Y-m', strtotime('-1 month')) : $start;
        $end = empty($end) ? date('Y-m') : $end;

        //转为时间戳
        $st = strtotime($start);
        $et = strtotime($end);

        $t = $st;
        $i = 0;
        $d = [];
        while ($t <= $et) {
            //这里累加每个月的的总秒数 计算公式：上一月1号的时间戳秒数减去当前月的时间戳秒数
            $d[$i] = trim(date('Y-m', $t), ' ');
            $t += strtotime('+1 month', $t) - $t;
            $i++;
        }
        return $d;
    }

    /**
     * 处理数据-管理人数
     * @param $data
     * @param $time
     * @param $qualityData
     * @return array|false
     */
    public static function stuffData($data, $time, $qualityData)
    {
        foreach ($data as $key => $val) {
            foreach ($time as $k => $v) {

                //总管理人数
                if ($k > date("Y-m", strtotime($val['created_at']))) {
                    $time[$k]['month_sum'][] = $val;
                    //总质控人数
                    if ($qualityData[$val['user_id']] == 1) {
                        $time[$k]['quality_sum'][] = $val;
                    }
                }

                //每月净增管理人数
                if ($k == date("Y-m", strtotime($val['created_at']))) {
                    $time[$k]['month'][] = $val;
                    $time[$k]['month_sum'][] = $val;
                    //每月净增质控人数
                    if ($qualityData[$val['user_id']] == 1) {
                        $time[$k]['quality'][] = $val;
                        $time[$k]['quality_sum'][] = $val;
                    }
                }
            }
        }

        $return = [];
        foreach ($time as $k => $v) {
            $return[$k]['quality'] = isset($time[$k]['quality']) ? count($time[$k]['quality']) : 0;
            $return[$k]['month'] = isset($time[$k]['month']) ? count($time[$k]['month']) : 0;
            $return[$k]['quality_sum'] = isset($time[$k]['quality_sum']) ? count($time[$k]['quality_sum']) : 0;
            $return[$k]['month_sum'] = isset($time[$k]['month_sum']) ? count($time[$k]['month_sum']) : 0;
        }

        return $return;
    }

    /**
     * 处理用户年龄
     * @param $data
     * @return mixed
     */
    public static function stuffAgeData($data)
    {
        $userIdArray = array_column($data, 'user_id');

        $list = ZUser::query()->selectRaw('id as user_id,sex,bday')
            ->whereIn('id', $userIdArray)
            ->get()->toArray();
        // 组装数据
        $tt = [0, 1, 2, 3, 4, 5, 6];
        $return = [];
        foreach ($tt as $k => $val) {
            $return[$k]['man'] = 0;
            $return[$k]['woman'] = 0;
        }
        //sex  0 男  1 女
        foreach ($list as $k => $v) {
            $v['bday'] = getBday($v['bday']);
            if ($v['bday'] < 30) {
                $key = 0;
            } elseif ($v['bday'] < 40) {
                $key = 1;
            } elseif ($v['bday'] < 50) {
                $key = 2;
            } elseif ($v['bday'] < 55) {
                $key = 3;
            } elseif ($v['bday'] < 60) {
                $key = 4;
            } elseif ($v['bday'] < 65) {
                $key = 5;
            } else {
                $key = 6;
            }
            if ($v['sex'] == 0) {
                $return[$key]['man']++;
            } else {
                $return[$key]['woman']++;
            }
        }

        return $return;
    }

    /**
     * 疾病史数据
     * @param $userId
     * @return array
     */
    public static function getIllnessData($userIds)
    {
        return ZPituitaryUser::query()
            ->from(self::ANSWER_TABLE)
            ->whereIn('subquestion_id', [138, 139, 140, 141, 143, 144, 146, 147, 148, 150, 151])
            ->whereIn('user_id', $userIds)
            ->where('visit_level', 1)
            ->get()
            ->toArray();
    }

    /**
     * 处理疾病史数据
     *
     *  糖尿病、高血压、高血脂、骨质疏松、心脑血管事件、恶性肿瘤、慢性肾脏疾病、呼吸系统疾病、阻塞性睡眠呼吸暂停低通气综合征、慢性肝脏疾病、感染性疾病
     * @param $data
     * @param $total
     * @return array 返回值类型
     */
    public static function stuffIllnessData($data, $total)
    {
        $ret = [];

        $answerKeys = [
            138 => 'one_num',
            139 => 'two_num',
            140 => 'three_num',
            141 => 'four_num',
            143 => 'five_num',
            144 => 'sex_num',
            146 => 'seven_num',
            147 => 'eight_num',
            148 => 'nine_num',
            150 => 'ten_num',
            151 => 'eleven_num',
        ];

        $keys = [
            13801 => 'one',
            13901 => 'two',
            14001 => 'three',
            14101 => 'four',
            1 => 'five',
            14401 => 'sex',
            14601 => 'seven',
            14701 => 'eight',
            14801 => 'nine',
            15001 => 'ten',
            15101 => 'eleven',
        ];

        foreach ($keys as $key => $v) {
            $ret[$v] = 0;
        }
        foreach ($answerKeys as $k => $v) {
            $ret[$v] = 0;
        }
        $fiveArr = [];
        // 遍历获取对应疾病的数量, 一个控制填写总数/一个控制患病数
        foreach ($data as $k => $v) {
            if (isset($keys[$v['answer_id']])){
                $ret[$keys[$v['answer_id']]]++;
            }
            //  特殊处理心血管时间，填了就代表1，去重后除于总数
            if ($v['subquestion_id'] == 143 ){
                $fiveArr[] = $v['user_id'];
            }
            if (isset($answerKeys[$v['subquestion_id']])){
                $ret[$answerKeys[$v['subquestion_id']]]++;
            }
        }
        $fiveArr = array_unique($fiveArr);

        $percent = [
            'one' => getScale($ret['one'], $ret['one_num']),
            'two' => getScale($ret['two'], $ret['two_num']),
            'three' => getScale($ret['three'], $ret['three_num']),
            'four' => getScale($ret['four'], $ret['four_num']),
            'five' => getScale(count($fiveArr), $total),
            'sex' => getScale($ret['sex'], $ret['sex_num']),
            'seven' => getScale($ret['seven'], $ret['seven_num']),
            'eight' => getScale($ret['eight'], $ret['eight_num']),
            'nine' => getScale($ret['nine'], $ret['nine_num']),
            'ten' => getScale($ret['ten'], $ret['ten_num']),
            'eleven' => getScale($ret['eleven'], $ret['eleven_num']),
        ];

        return $percent;
    }


}